/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 */

import path from 'path';

import { NodeCommandBuilder } from '../../builder/node-command-builder.js';
import { OhosLogger } from '../../utils/log/ohos-logger.js';
import { ProcessUtils } from '../../utils/process-utils.js';
import { ArkComponent } from '../superior/ark-component.js';

/**
 * js ark实例
 *
 * @since 2021-12-16
 */
export class EtsArkComponent implements ArkComponent {
  private _log: OhosLogger = OhosLogger.getLogger(EtsArkComponent.name);
  private readonly _ets2abcToolPath: string;

  private ets2abcVersion = '';

  constructor(etsLoaderPath: string) {
    this._ets2abcToolPath = path.resolve(etsLoaderPath, 'bin', 'ark', 'ts2abc.js');
  }

  getArkVersion(compatibleSdkVersion?: number, compatibleSdkVersionStage?: string): string {
    if (this.ets2abcVersion !== '') {
      return this.ets2abcVersion;
    }

    try {
      const nodeCommandBuilder = new NodeCommandBuilder().addJsPath(this._ets2abcToolPath);
      if (compatibleSdkVersion) {
        nodeCommandBuilder.getCompatibleTsVersion(compatibleSdkVersion);
        // compatibleSdkVersionStage与compatibleSdkVersion配套使用
        if (compatibleSdkVersionStage) {
          nodeCommandBuilder.getCompatibleSdkVersionStage(compatibleSdkVersionStage);
        }
      } else {
        nodeCommandBuilder.getTsVersion();
      }
      this._log.debug(nodeCommandBuilder.build());
      this.ets2abcVersion = new ProcessUtils()
        .executeSync(nodeCommandBuilder.build(), {
          stdio: 'pipe',
        })
        .stdout.toString();
      return this.ets2abcVersion.trim();
    } catch (e) {
      this._log.debug('Execute command error.Cannot get ark version.');
      return '';
    }
  }
}
